<template>
	<view class="nickname">
		<gyd-navbar back-color="#fff" :title="title"></gyd-navbar>

		<view class="content">
			<view class="form"><u-input v-model="nickname"></u-input></view>
			<view class="btn" @click="saveName">保存</view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const state = reactive({
		title: '修改昵称',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		loading: false,
		nickname: '',
	});

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		if (opt.hasOwnProperty('nickname')) {
			console.log('传递参数', opt.nickname);
			state.nickname = opt.nickname;
		}
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	})

	onReachBottom(() => {
		console.log('触底加载更多');
	})

	function saveName() {
		if (!state.nickname) {
			util.showTip("请输入新的昵称");
			return;
		}
		if (state.loading) {
			util.showTip("请不要重复提交");
			return;
		}
		state.loading = true;

		let params = {
			nickname: state.nickname,
			role: cache.get('role', false),
		};

		request.post("userinfo/member_set", params)
			.then(res => {
				util.showTip(res.msg);
				if (res.code === 1) {
					setTimeout(() => {
						pageTabRoute('/merchantPages/profile/profile');
					}, 800);
				}
			})
			.catch(err => {
				util.showTip(err.msg);
			})
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		loading,
		nickname,
	} = toRefs(state);
</script>

<style lang="scss">
	page {
		background-color: $u-bg-color;
	}

	.nickname {
		padding: $m32;
		background-color: $u-bg-reverse-color;

		.content {
			.form {
				border-bottom: #f7f7fb solid 1rpx;
				margin: 0 0 20rpx 0;
			}

			.btn {
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 40rpx;
				background: linear-gradient(to right, #125cd7, #279dfa);
				color: #fff;
				text-align: center;
			}
		}
	}
</style>